package it.oneb.study.mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DbConfig {
	
	private String jdbcUrl;
	
	private Connection connection;
	
	/**
	 * 打开数据库连接
	 * @return
	 */
	public Connection openConnection() {
		if (connection == null) {
			generateConnect();			
		}
		
		System.out.println("connection get: " +connection);
		return connection;
	}
	
	/**
	 * 关闭数据库连接
	 */
	public void closeConnection() {
		try {
			connection.close();
			connection = null;
		} catch (SQLException e) {
			// TODO: handle exception
		}
		
	}
	
	
	public ResultSet querySql(String sql)
	{
		ResultSet rSet = null;
		// 由数据库连接产生SQL陈述对象
		try {
			Statement statement = connection.createStatement();
			rSet =  statement.executeQuery(sql);
		} catch (SQLException e) {
			System.out.println("query sql failed: " + e.getMessage());
		}
		
		return rSet;
		
		
	}
	
	public DbConfig(String jdbcUrl)
	{
		this.jdbcUrl = jdbcUrl;
		generateConnect();
	}
	
	
	private void generateConnect()
	{
		/*
		 * DriverManager：驱动管理器，负责 建立 数据库链接。 
			Connection:代表数据库链接 
			Statement：负责执行SQL语句 
			PreparedStatement：负责 执行SQL语句，具有预定义的功能。 
			ResultSet：表示查询结果的记录集。

		 * 
		 */
		try 
		{
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection(jdbcUrl);
			System.out.println("connection generated: " + connection);
			
		}
		catch (Exception e) 
		{
			System.out.println("connection failed: "+ e.getMessage());
		}
		
		
	}

}
